package com.ruoyi.auth.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.auth.MyThread.Mythread;
import com.ruoyi.auth.form.PCWeiXin;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.xml.transform.Source;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * wx ：读取Appid相关配置信息静态类
     */
    @Autowired
    private PCWeiXin constants;

    @Value("${login.allow}")
    private boolean allow;

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
//        /*登录失败次数*/
//        Integer errorSize = redisService.getCacheObject("error:" + username);
//        if (errorSize != null) {
//            if (errorSize >= 10) {
//                throw new ServiceException("登录失败次数到达上限，请明天再试");
//            }
//        } else {
//            errorSize = 0;
//            /*初始化*/
//            redisService.setCacheObject("error:" + username, 0, endTimeDiff(), TimeUnit.MILLISECONDS);
//        }


        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
//            redisService.setCacheObject("error:" + username, errorSize + 1, endTimeDiff(), TimeUnit.MILLISECONDS);
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
//            redisService.setCacheObject("error:" + username, errorSize + 1, endTimeDiff(), TimeUnit.MILLISECONDS);
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }


        /*单点登录*/
//        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
//        for (String key : keys)
//        {
//            LoginUser y = redisService.getCacheObject(key);
//            if (y.getUsername().equals(user.getUserName())){
//                redisService.deleteObject(key);
//            }
//        }

        /*单点登录*/
        if (allow){
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            Mythread mythread = new Mythread();
            mythread.setUserName(user.getUserName());
            mythread.setRedisService(redisService);
            mythread.setKeys(keys);
            mythread.start();
        }

        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public LoginUser weixinPclogin(String openId, String access_token) {

        // 授权成功 --> 根据token和openId获取微信用户信息
        JSONObject infoJson = this.getUserInfo(access_token, openId);

        openId = infoJson.getString("id");
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfoByOpenId(openId, SecurityConstants.INNER);
//
//        if (R.FAIL == userResult.getCode()) {
//            throw new ServiceException(userResult.getMsg());
//        }

        if (R.FAIL == userResult.getCode()) {

            // 注册用户信息
            SysUser sysUser = new SysUser();
            sysUser.setUserName(openId);
            sysUser.setNickName(String.valueOf(infoJson.get("nickName")));
            sysUser.setAvatar(String.valueOf(infoJson.get("avatar")));
            sysUser.setOpenId(openId);
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            R<Boolean> info = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
            userResult = remoteUserService.getUserInfoByOpenId(openId, SecurityConstants.INNER);
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();


        /*单点登录*/
        if (allow){
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            Mythread mythread = new Mythread();
            mythread.setUserName(user.getUserName());
            mythread.setRedisService(redisService);
            mythread.setKeys(keys);
            mythread.start();
        }


        return userInfo;
    }


    /**
     * 登录
     */
    public LoginUser loginCode(String username, String code) {
        /*登录失败次数*/
        Integer errorSize = redisService.getCacheObject("error:" + username);
        if (errorSize != null) {
            if (errorSize >= 10) {
                throw new ServiceException("登录失败次数到达上限，请明天再试");
            }
        } else {
            errorSize = 0;
            /*初始化*/
            redisService.setCacheObject("error:" + username, 0, endTimeDiff(), TimeUnit.MILLISECONDS);
        }

        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            redisService.setCacheObject("error:" + username, errorSize + 1, endTimeDiff(), TimeUnit.MILLISECONDS);
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            redisService.setCacheObject("error:" + username, errorSize + 1, endTimeDiff(), TimeUnit.MILLISECONDS);
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        /*判断验证码*/
        String codes = redisService.getCacheObject("loginCode:" + username);
        if (codes != null) {
            if (code.equals(codes)) {

            } else {
                redisService.setCacheObject("error:" + username, errorSize + 1, endTimeDiff(), TimeUnit.MILLISECONDS);
                throw new RuntimeException("验证码不正确");
            }
        } else {
            throw new RuntimeException("验证码已过期，请重新获取");
        }

        /*单点登录*/
//        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
//        for (String key : keys)
//        {
//            LoginUser y = redisService.getCacheObject(key);
//            if (y.getUsername().equals(user.getUserName())){
//                redisService.deleteObject(key);
//            }
//        }

        /*单点登录*/
        if (allow){
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            Mythread mythread = new Mythread();
            mythread.setUserName(user.getUserName());
            mythread.setRedisService(redisService);
            mythread.setKeys(keys);
            mythread.start();
        }



        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * 获取生成的二维码url连接
     * <p>
     * appid：公众号的唯一标识
     * redirect_uri：授权后重定向的回调链接地址
     * response_type：返回类型，填写code
     * scope：应用授权作用域，snsapi_base，snsapi_userinfo
     * state：非必传，重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * wechat_redirect：无论直接打开还是做页面302重定向时候，必须带此参数
     *
     * @return
     * @author wangsong
     * @date 2019年6月19日 下午5:55:36
     */
    public String getAuthorizationUrl(String type, String state) {
        // url
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
        String callbackUrl = "";
        Object urlState = "";
        try {
            if ("pc".equals(type)) {
                // pc端回调方法（没处理，我这里回调一致）
                System.out.println("constants.getWeCatRedirectUrl() = " + constants.getWeCatRedirectUrl());
                callbackUrl = URLEncoder.encode(constants.getWeCatRedirectUrl() + "/prod-api/auth/wx/pcAuth", "utf-8");
                System.out.println("callbackUrl = " + callbackUrl);
                urlState = state;
            } else if ("mobile".equals(type)) {
                // pc端回调方法
                callbackUrl = URLEncoder.encode(constants.getWeCatRedirectUrl() + "/prod-api/auth/wx/pcAuth", "utf-8");
                System.out.println("callbackUrl = " + callbackUrl);
                urlState = System.currentTimeMillis();
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 权限 snsapi_userinfo snsapi_base
        String scope = "snsapi_userinfo";
        url = String.format(url, constants.getWeCatAppId(), callbackUrl, scope, urlState);
        return url;
    }

    /**
     * 获取 token, openId（token有效期2小时）
     *
     * @param code
     * @return
     * @author wangsong
     * @date 2019年6月19日 下午5:55:11
     */
    public String getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url, constants.getWeCatAppId(), constants.getWeCatAppSecret(), code);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        String resp = getRestTemplate().getForObject(uri, String.class);
        if (resp.contains("openid")) {
            JSONObject jsonObject = JSONObject.parseObject(resp, JSONObject.class);
            String access_token = jsonObject.getString("access_token");
            String openId = jsonObject.getString("openid");
            JSONObject res = new JSONObject();
            res.put("access_token", access_token);
            res.put("openId", openId);
            res.put("refresh_token", jsonObject.getString("refresh_token"));
            return res.toJSONString();
        } else {
            return null;
        }
    }

    /**
     * 微信接口中，token和openId是一起返回，故此方法不需实现
     *
     * @param accessToken
     * @return
     */
    public String getOpenId(String accessToken) {
        return null;
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public JSONObject getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
        url = String.format(url, accessToken, openId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();
        String resp = getRestTemplate().getForObject(uri, String.class);
        if (resp.contains("errcode")) {
            return null;
        } else {
            JSONObject data = JSONObject.parseObject(resp, JSONObject.class);
            JSONObject result = new JSONObject();
            result.put("id", data.getString("unionid"));
            result.put("sex", data.getString("sex"));
            result.put("nickName", data.getString("nickname"));
            result.put("avatar", data.getString("headimgurl"));
            return result;
        }
    }

    /**
     * 微信的token只有2小时的有效期，过时需要重新获取，所以官方提供了,根据refresh_token
     * 刷新获取token的方法，本项目仅仅是获取用户，信息，并将信息存入库，所以两个小时也已经足够了
     *
     * @param refresh_token
     * @return
     * @author wangsong
     * @date 2019年6月19日 下午5:34:07
     */
    public String refreshToken(String refresh_token) {
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";
        url = String.format(url, constants.getWeCatAppId(), refresh_token);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();
        ResponseEntity<JSONObject> resp = getRestTemplate().getForEntity(uri, JSONObject.class);
        JSONObject jsonObject = resp.getBody();
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }

    /**
     * @return
     * @author wangsong
     * @date 2019年6月19日 下午5:35:43
     */
    public static RestTemplate getRestTemplate() {// 手动添加
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(120000);
        List<HttpMessageConverter<?>> messageConverters = new LinkedList<>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter<Source>());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }


    /**
     * 结束时间
     *
     * @return
     */
    private Long endTimeDiff() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}
